//
//  THShootAnimateView.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 HZMengLiao. All rights reserved.
//
#import "THShootAnimateView.h"
//#import <CoreMotion/CoreMotion.h>

#define HQMaxCollisionCount 3
@interface HQDropItemView : UIView

@property (nonatomic ,strong) UIImageView *imgV;

@property (nonatomic, assign) NSInteger count;

@end

@implementation HQDropItemView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self createUI];
    }
    return self;
}

- (void)createUI
{
    _imgV = [[UIImageView alloc] init];
    [self addSubview:_imgV];
}

- (void)addTopViewRotationAnimation
{
    float random = ((int)((arc4random() % 6)))*0.1 - 0.3;
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * random];
    rotationAnimation.duration = 0.3;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = HUGE_VALF;
    [self.imgV.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

@end

@interface THShootAnimateView()<UIAccelerometerDelegate,UICollisionBehaviorDelegate,UIDynamicAnimatorDelegate>

@property (nonatomic , strong) UIDynamicAnimator        * animator;
// 重力
@property (nonatomic , strong) UIGravityBehavior        * gravityBehavior;
// 碰撞
@property (nonatomic , strong) UICollisionBehavior      * collisionBehavitor;

@property (nonatomic , strong) UIDynamicItemBehavior    * itemBehavitor;

//@property (nonatomic, strong)  CMMotionManager * motionMManager;

@property (strong,nonatomic)   NSMutableArray *dropsArray;

@property (nonatomic, strong) dispatch_source_t timer;


@property (nonatomic, assign) BOOL isDropping;

@property (nonatomic, assign) HQShootStartPosition shootPosition;

@property (nonatomic, assign) NSInteger count; //掉落的个数

@end

@implementation THShootAnimateView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self createUI];
//        _motionMManager = [[CMMotionManager alloc] init];
//        [self startMotion];
    }
    return self;
}

- (void)createUI
{
    _count = 20;
    self.backgroundColor = [UIColor grayColor];
    self.clipsToBounds = YES;
    _shootPosition = HQShootStartPositionTopLine;
    self.backgroundColor = [UIColor clearColor];
    self.userInteractionEnabled = NO;
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    if (!newSuperview) {
        [self clearAll];
    }
}

- (void)addMixBullet:(NSArray<UIImage *> *)imageArray
{
    NSMutableArray *viewArray = [[NSMutableArray alloc] init];
    for (int i = 0 ; i < _count; i++) {
        HQDropItemView *itemView = [[HQDropItemView alloc] init];
        
        itemView.contentMode = UIViewContentModeCenter;
        itemView.size = CGSizeMake(HQDropItemViewSize, HQDropItemViewSize);//大小固定，方便控制推力大小
        if (_shootPosition == HQShootStartPositionLeftRightPoint) {
            itemView.center = CGPointMake(i%2==0 ? 0 : self.bounds.size.width, kStatusBarHeight + 44 + 25 + arc4random() % (250));
            itemView.tag = i%2;
        }else{
            CGFloat x = (int)(arc4random()%((int)self.bounds.size.width - 20)) + 10;//左右各留10pt间隙
            itemView.center = CGPointMake(x, 0);//
            itemView.tag = i%2;
        }
        itemView.imgV.image =  imageArray[i%imageArray.count];
        itemView.imgV.frame = CGRectMake(0, 0, itemView.size.width, itemView.size.height);
        [viewArray addObject:itemView];
    }
    [self.dropsArray addObject:viewArray];
}


//添加喷射的子弹
- (void)addBullet:(UIImage *)image
{
    NSMutableArray *viewArray = [[NSMutableArray alloc] init];
    for (int i = 0 ; i < _count; i++) {
        HQDropItemView *itemView = [[HQDropItemView alloc] init];
        
        itemView.contentMode = UIViewContentModeCenter;
        itemView.size = CGSizeMake(HQDropItemViewSize, HQDropItemViewSize);//大小固定，方便控制推力大小
        if (_shootPosition == HQShootStartPositionLeftRightPoint) {
            itemView.center = CGPointMake(i%2==0 ? 0 : self.bounds.size.width, kStatusBarHeight + 44 + 25 + arc4random() % (250));
            itemView.tag = i%2;
        }else{
            CGFloat x = (int)(arc4random()%((int)self.bounds.size.width - 20)) + 10;//左右各留10pt间隙
            itemView.center = CGPointMake(x, 0);//
            itemView.tag = i%2;
        }
        
        itemView.imgV.image =  image;
        itemView.imgV.frame = CGRectMake(0, 0, itemView.size.width, itemView.size.height);

//        itemView.frame = CGRectMake(0,0, itemView.size.width, itemView.size.height);
//        [itemView addSubview:itemView];
        
        [viewArray addObject:itemView];
    }
//     ();
    [self.dropsArray addObject:viewArray];
}

- (void)addRotationAnimation:(UIView *)view
{
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: view.tag == 0 ? M_PI * 2.0 : -M_PI * 2.0];
    rotationAnimation.duration = 0.5;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = HUGE_VALF;
    [view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}



//发射子弹
- (void)topLineFire:(NSArray<UIImage *> *)image count:(NSInteger)count;
{
    _count = count;
    _shootPosition = HQShootStartPositionTopLine;
    [self.dropsArray removeAllObjects];
    [self addMixBullet:image];
    [self shootFire];
}

- (void)leftRightFire:(NSArray<UIImage *> *)image  count:(NSInteger)count;
{
    _count = count;
    _shootPosition = HQShootStartPositionLeftRightPoint;
    [self.dropsArray removeAllObjects];
    [self addMixBullet:image];
    [self shootFire];
}

- (void)topLineFire:(UIImage *)image
{
    _shootPosition = HQShootStartPositionTopLine;
    [self.dropsArray removeAllObjects];
    [self addBullet:image];
    [self shootFire];
}

- (void)leftRightFire:(UIImage *)image
{
    _shootPosition = HQShootStartPositionLeftRightPoint;
    [self.dropsArray removeAllObjects];
    [self addBullet:image];
    [self shootFire];
}

//发射子弹
- (void)shootFire
{
    if (_isDropping)
    {
        return;
    }
    _isDropping = YES;
    dispatch_queue_t queue = dispatch_get_main_queue();
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));/**< 延迟一秒执行*/
    uint64_t interval = (uint64_t)(0.05 * NSEC_PER_SEC);
    dispatch_source_set_timer(self.timer, start, interval, 0);
    // 设置回调
    @weakify(self);
    dispatch_source_set_event_handler(self.timer, ^{
        @strongify(self);
        if (self.dropsArray.count == 0){
            return;
        }
        NSMutableArray *currentDrops = self.dropsArray[0];
        if ([currentDrops count]) {
            if (currentDrops.count == 0){
                return;
            }
            HQDropItemView * dropView = currentDrops[0];
            [currentDrops removeObjectAtIndex:0];
            [self addSubview:dropView];
            UIPushBehavior *pushBehavior = [[UIPushBehavior alloc] initWithItems:@[dropView] mode:UIPushBehaviorModeInstantaneous];
            [self.animator addBehavior:pushBehavior];
            if (self.shootPosition == HQShootStartPositionLeftRightPoint) {//两边射出
                float randomY = ((int)((arc4random() % 4)))*0.1 - 0.1;
                pushBehavior.pushDirection = CGVectorMake(dropView.tag == 0 ? 1 : -1,randomY);
                pushBehavior.magnitude = 5;//2.5
                [self addRotationAnimation:dropView];

            }else{
                //角度范围 ［-0.2 +0.2］
                float random = ((int)((arc4random() % 4)))*0.1 - 0.2;
                pushBehavior.pushDirection = CGVectorMake(random,1);
                pushBehavior.magnitude = 0.2;
                [dropView addTopViewRotationAnimation];
            }

            [self.gravityBehavior addItem:dropView];
            [self.collisionBehavitor addItem:dropView];
            [self.itemBehavitor addItem:dropView];
            if (self.shootPosition == HQShootStartPositionLeftRightPoint) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [UIView animateWithDuration:.1 animations:^{
                        dropView.alpha = 0;
                        [self.gravityBehavior removeItem:dropView];
                        [self.collisionBehavitor removeItem:dropView];
                        [self.itemBehavitor removeItem:dropView];
                        [pushBehavior removeItem:dropView];
                        [self.animator removeBehavior:pushBehavior];
                    }completion:^(BOOL finished) {
                        [dropView removeFromSuperview];
                    }];
                });
            }
        }else{
            dispatch_source_cancel(self.timer);
            [self.dropsArray removeObject:currentDrops];
            self.isDropping = NO;
            if (self.dropsArray.count) {
                [self shootFire];
            }
        }
        
    });
    dispatch_source_set_cancel_handler(_timer, ^{
//        if (self.shootPosition == HQShootStartPositionLeftRightPoint) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                if (self.complete) self.complete();
//                [self removeFromSuperview];
//            });
//        }
    });
    //启动
    dispatch_resume(self.timer);
}

#pragma mark instance methods
//- (void)startMotion
//{
//    if(_motionMManager.accelerometerAvailable)
//    {
//        if (!_motionMManager.accelerometerActive)
//        {
//            _motionMManager.accelerometerUpdateInterval = 1.0/3.0;
//            __unsafe_unretained typeof(self) weakSelf = self;
//            [_motionMManager
//             startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
//             withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
//
//                 if (error)
//                 {
//                     NSLog(@"CoreMotion Error : %@",error);
//                     [self.motionMManager stopAccelerometerUpdates];
//                 }
//                 CGFloat a = accelerometerData.acceleration.x;
//                 CGFloat b = accelerometerData.acceleration.y;
//                 CGVector gravityDirection = CGVectorMake(a,-b);
//                 weakSelf.gravityBehavior.gravityDirection = gravityDirection;
//             }];
//        }
//
//    }
//    else
//    {
//        NSLog(@"The accelerometer is unavailable");
//    }
//}



///清空所有
- (void)clearAll
{
    // 停止陀螺仪
//    [_motionMManager stopAccelerometerUpdates];
    _isDropping = NO;
    if (_timer) {
        dispatch_cancel(_timer);
        _timer = nil;
    }
    for (UIDynamicBehavior *behavior in _animator.behaviors)
    {
        if (behavior == self.gravityBehavior)
        {
            for (UIImageView *v in self.gravityBehavior.items)
            {
                [self.gravityBehavior removeItem:v];
                if (v.superview)[v removeFromSuperview];
            }
            continue;
        }
        else if (behavior == self.collisionBehavitor)
        {
            for (UIImageView *v in self.collisionBehavitor.items) {
                [self.collisionBehavitor removeItem:v];
                if (v.superview)[v removeFromSuperview];
            }
            continue;
        }
        else [_animator removeBehavior:behavior];;
    }
    self.animator = nil;
    [self.dropsArray removeAllObjects];
}

// The identifier of a boundary created with translatesReferenceBoundsIntoBoundary or setTranslatesReferenceBoundsIntoBoundaryWithInsets is nil
- (void)collisionBehavior:(UICollisionBehavior*)behavior beganContactForItem:(id <UIDynamicItem>)item withBoundaryIdentifier:(nullable id <NSCopying>)identifier atPoint:(CGPoint)p
{
    if (p.y < self.height - 20) {//不是底部的碰撞
        return;
    }
//    if (self.shootPosition == HQShootStartPositionTopLine) {
        HQDropItemView *dropView = (HQDropItemView *)item;
        dropView.count ++;
        if (dropView.count == HQMaxCollisionCount) { //最后一次碰撞，需要移除
            [self.gravityBehavior removeItem:dropView];
            [self.collisionBehavitor removeItem:dropView];
            [self.itemBehavitor removeItem:dropView];
            [dropView removeFromSuperview];
        }
//    }

}
- (void)collisionBehavior:(UICollisionBehavior*)behavior endedContactForItem:(id <UIDynamicItem>)item withBoundaryIdentifier:(nullable id <NSCopying>)identifier
{
    NSLog(@"%s--point:-- %@",__func__,behavior);
    if (self.shootPosition == HQShootStartPositionTopLine) {
        HQDropItemView *dropView = (HQDropItemView *)item;
        if (dropView.count == HQMaxCollisionCount-1) {
            dropView.y = dropView.y - dropView.height;
            dropView.imgV.frame = CGRectMake(0, dropView.height, dropView.width, dropView.height);
            [self.animator updateItemUsingCurrentState:item];
        }
    }
}

- (void)dynamicAnimatorWillResume:(UIDynamicAnimator *)animator
{
    
}
- (void)dynamicAnimatorDidPause:(UIDynamicAnimator *)animator
{
    
}

- (UIDynamicAnimator *)animator{
    if (!_animator) {
        _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self];
        /** 重力效果*/
        self.gravityBehavior = [[UIGravityBehavior alloc] init];
//        self.gravityBehavior.magnitude = 0.01;
        //        self.gravityBehavior.gravityDirection = CGVectorMake(0.5,1);
        /** 碰撞效果*/
        self.collisionBehavitor = [[UICollisionBehavior alloc] init];
        self.collisionBehavitor.collisionDelegate = self;
        if (_shootPosition == HQShootStartPositionLeftRightPoint) {
            [self.collisionBehavitor setTranslatesReferenceBoundsIntoBoundary:NO];
            self.collisionBehavitor.collisionMode = UICollisionBehaviorModeBoundaries;
        }else{
            self.collisionBehavitor.collisionMode = UICollisionBehaviorModeBoundaries;
            [self.collisionBehavitor setTranslatesReferenceBoundsIntoBoundary:YES];
//            [self.collisionBehavitor setTranslatesReferenceBoundsIntoBoundaryWithInsets:UIEdgeInsetsMake(0, 0, _insets.bottom, 0)];
        }
        @weakify(self);
        self.collisionBehavitor.action = ^{
            @strongify(self);
//            if (self.shootPosition == HQShootStartPositionTopLine) {
                    if (self.collisionBehavitor.items.count <= 0) {
                //        执行完了
                        KExecuteBlock(self.complete);
                        [self removeFromSuperview];
                    }
//            }
        };
//        碰撞item
        self.itemBehavitor = [[UIDynamicItemBehavior alloc] init];
        self.itemBehavitor.elasticity   = 0.9; // 改变弹性
        self.itemBehavitor.friction     = 0.6; // 摩擦
        self.itemBehavitor.resistance   = 0.6; // 阻力
        
        [_animator addBehavior:self.gravityBehavior];
        [_animator addBehavior:self.collisionBehavitor];
        [_animator addBehavior:self.itemBehavitor];
        _animator.delegate = self;
    }
    return _animator;
}

-(NSMutableArray *)dropsArray
{
    if (!_dropsArray) {
        _dropsArray = @[].mutableCopy;
    }
    return _dropsArray;
}


-(void)dealloc{
    NSLog(@"dealloc");
}


@end
